

#import "UIImage+cate.h"

@implementation UIImage (cate)
+ (nullable NSURLSessionTask *)imageWithURL:(NSString *)url block:(void(^)(UIImage *image))block
{
    NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"url"),bg_sqlValue(url)];
    NSArray* resultArr = [KImage bg_find:nil where:where];
    if (block) {
        if ([resultArr count] > 0) {
            KImage *img = resultArr[0];
            if (img.data != nil) {
                block([UIImage imageWithData:img.data]);
                return nil;
            }
        }
        if (url.length
            <= 0) {
            return nil;
        }
        
        return [network get:url para:nil header:nil success:^(id  _Nonnull response) {
           UIImage *img = [self imageWithImage:response scaledToSize:CGSizeMake(500, 500)];
            KImage *model = [KImage new];
            model.url = url;
            model.data = UIImageJPEGRepresentation(img, 0.1);
            [KImage bg_saveOrUpdateArrayAsync:@[model] complete:^(BOOL isSuccess) {
            }];
            block((UIImage *)response);
        } fail:^(NSError * _Nonnull error) {
            
        }];
    }
    return [[NSURLSessionTask alloc] init];;
}
+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0, 0, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
//压缩图片
#pragma mark - /压缩图片
+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}


#pragma mark - UIImage转换成base64
- (NSString *)base64
{
    NSData *data = UIImagePNGRepresentation(self);
    return [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
}

- (NSData *)compressWithImage:(UIImage *)originImage length:(NSInteger)length {
    NSInteger  maxLength = length*1024;
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(originImage, compression);
    //NSLog(@"Before compressing quality, image size = %ld KB",data.length/1024);
    if (data.length < maxLength) return data;
    
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(originImage, compression);
        //NSLog(@"Compression = %.1f", compression);
        //NSLog(@"In compressing quality loop, image size = %ld KB", data.length / 1024);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    //NSLog(@"After compressing quality, image size = %ld KB", data.length / 1024);
    if (data.length < maxLength) return data;
    UIImage *resultImage = [UIImage imageWithData:data];
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        //NSLog(@"Ratio = %.1f", ratio);
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
        //NSLog(@"In compressing size loop, image size = %ld KB", data.length / 1024);
    }
    //NSLog(@"After compressing size loop, image size = %ld KB", data.length / 1024);
    return data;
}
@end
